ig.module(
	'game.gameTypes.gameConnection'
)
.requires(
	'impact.game',
	'game.gameTypes.gameBase',
	'game.entities.base.baseFood',
	'game.entities.base.pickObject',
	'game.entities.playButton',	
	'game.entities.base.question',
	'game.entities.optionButton',
	'game.entities.linkButton'
)
.defines(function ()
{
    GameConnection = GameBase.extend(
    {
        questionFont: new ig.Font('media/fonts/arial10.png'),	
        font12: new ig.Font('media/fonts/arial12.png'),
	
        timer: new ig.Timer(),
        gameTimer: new ig.Timer(),

        init: function ()
	{
            this.parent();
	    
            ig.global.numberOfPicks = 0
            ig.global.validPicks = 0;
            ig.global.failed = false;
            ig.global.paused = true;
            ig.global.started = false;
            ig.global.justStarted = false;
            ig.global.finished = false;
            ig.global.justFinished = false;
	    ig.global.questions = new Array();
	    ig.global.fullQuestion = new Array();
	    ig.global.currentQuestion = 0;
	    ig.global.numberOfQuestions = 0;
	    ig.global.totalTime = 3000;
	    ig.global.questionChanged = false;
	    ig.global.accessDenied  = false;
	    ig.global.testID = -1;
	    ig.global.studentID = -1;
	    ig.global.submited = false;
	    ig.global.maxQuestionWidth = 800;
	    ig.global.maxOptionWidth = 410;	    
	    ig.global.totalPoints = 0.0;
	    ig.global.questionChanged = true;
	    ig.global.mode = 0;
	    ig.global.cpf = "0";
	    
	    ig.global.submitAnswers = function()
	    {
		var answers = '';		
		for (i = 0; i < ig.global.numberOfQuestions; ++i)
		{
		    var question = ig.global.fullQuestion[i];
		    answers += '' + question.userAnswer;
		}
		
		window.location = "Completed.aspx?s=" + answers + "&g=" + ig.global.testID + "&k=" + ig.global.studentID + "&i=" + ig.global.mode + "&v=" + ig.global.cpf;
		alert("A prova foi submetida para avaliação.");
	    }
        },

        postInit: function ()
	{
	    this.setupQuestions();
	    
            ig.global.validPicks = ig.global.questions.length + 10;
        },

	setupQuestions: function ()
	{
	    if (
		     document.getElementById("transferArea").value == ""
		  || document.getElementById("additionalData").value == ""
	       )
	    {
		ig.global.accessDenied = true;
		ig.game.getEntitiesByType(EntityPlayButton)[0].kill();
			
		return;		
	    }
	    
	    var additionalData = document.getElementById("additionalData").value.split("#");
	    ig.global.testID = additionalData[0];
	    ig.global.studentID = additionalData[1];
	    ig.global.totalTime = parseFloat(additionalData[2]);
	    
	    if (additionalData.length == 4)
	    {
		ig.global.mode = 1;
	    }
	    
	    // Cpf
	    ig.global.cpf = document.getElementById("customData").value;	    
	    
	    // Size of the question canvas: 600 x 80	    
	    // Loading the questions
	    var questions = document.getElementById("transferArea").value.split("Ą");
	    ig.global.questions = document.getElementById("transferArea").value.split("Ą");	
	    
	    ig.global.fullQuestion = new Array(ig.global.questions.length);	    
	    for (var i = 0; i < ig.global.questions.length; ++i)
    	    {		
		var questionData = ig.global.questions[i].split("Ę");
		
		if (questionData[0].length <= 0)
		{
		    break;
		}
		
		var fullQuestion = new EntityQuestion();
		fullQuestion.text = questionData[0];
		
		fullQuestion.one = this.ajustTextString(questionData[1], ig.global.maxOptionWidth);
		fullQuestion.two = this.ajustTextString(questionData[2], ig.global.maxOptionWidth);
		fullQuestion.three = this.ajustTextString(questionData[3], ig.global.maxOptionWidth);
		fullQuestion.four = this.ajustTextString(questionData[4], ig.global.maxOptionWidth);
		
		fullQuestion.value =  questionData[5];
		fullQuestion.userAnswer = 0;
		ig.global.fullQuestion[i] = fullQuestion;		
		
		ig.global.totalPoints += parseFloat(fullQuestion.value.replace(",", "."));
	    }
	    
	    ig.global.numberOfQuestions = ig.global.questions.length;	
	},    
	
        update: function ()
	{
            this.parent();
	    	    
	    if (ig.global.accessDenied == true)
	    {
		//this.font12.draw('Voce não está autorizado a realizar esta avaliação. ', 246, 65, ig.Font.ALIGN.LEFT);
		return		
	    }
	    
	    if (ig.global.totalTime  - this.gameTimer.delta() <= 0)	    
	    {
		if (ig.global.submited == false)
		{
		    ig.global.submitAnswers();
		    ig.global.submited = true;
		}		
	    }
        },

        pausedUpdate: function ()
	{
            if (ig.global.justFinished == true)
	    {
                ig.finished = true;
                ig.global.justFinished = false;

                ig.game.spawnEntity(EntityReplayButton, 488, 180);
                ig.game.sortEntitiesDeferred();
            }
        },

        draw: function ()
	{
            this.parent();
	   
	    if (ig.global.accessDenied == true)
	    {
		//this.font12.draw('Voce não está autorizado a realizar esta avaliação. ', 246, 65, ig.Font.ALIGN.LEFT);
		return		
	    }
	    
            if (ig.global.started == false)
	    {
		//this.font12.draw('Agora iremos avaliar o conhecimento adquirido por você durante o curso.\nClique em Iniciar para dar sequência.\n\nValor da avaliação: ' + ig.global.totalPoints, 230, 27, ig.Font.ALIGN.LEFT);
                return;
            }
            else if (ig.global.justStarted == true)
	    {
                this.timer.set(0);
                this.gameTimer.set(0);
                ig.global.justStarted = false;
		
		ig.game.getEntitiesByType(EntityPlayButton)[0].kill();
            }

            if (ig.global.numberOfPicks == ig.global.validPicks)
	    {
                ig.global.paused = true;

                if (ig.global.finished == false)
		{
                    ig.global.justFinished = true;
                    ig.global.finished = true;
                }

                this.font12.draw('Sucesso !!!', 400, 34, ig.Font.ALIGN.LEFT);
            }
            else if (ig.global.failed == true)
	    {
                ig.global.paused = true;

                if (ig.global.finished == false)
		{
                    ig.global.justFinished = true;
                    ig.global.finished = true;
                }
            }
            else
	    {
		if(ig.global.mode != 1)
		{
		    this.font12.draw('Tempo: ' + this.secondsToMinutes(ig.global.totalTime  - this.gameTimer.delta()), 700, 250, ig.Font.ALIGN.LEFT);
		}
                this.drawQuestion();	    
            }
        },

        drawQuestion: function ()
	{
	    if (ig.global.questionChanged == true)
	    {		
		ig.global.questionChanged = false;

		// Filling the question into the proper div		
		$('#questionDiv').html("" + (ig.global.currentQuestion + 1) + ") " + ig.global.fullQuestion[ig.global.currentQuestion].text);			
		
		var buttons = ig.game.getEntitiesByType(EntityOptionButton);
		
		for (var i = 0; i < buttons.length; ++i)
		{
		    buttons[i].selected = false;		    
		    switch (buttons[i].option)
		    {
			case 1:			    
			    buttons[i].text = ig.global.fullQuestion[ig.global.currentQuestion].one;
			    
			    if (ig.global.fullQuestion[ig.global.currentQuestion].userAnswer == buttons[i].option)
			    {
				buttons[i].selected = true;
			    }
		
			    break;
			
			case 2:			    
			    buttons[i].text = ig.global.fullQuestion[ig.global.currentQuestion].two;
			    
			    if (ig.global.fullQuestion[ig.global.currentQuestion].userAnswer == buttons[i].option)
			    {
				buttons[i].selected = true;
			    }
			    
			    break;
			
			case 3:			    
			    buttons[i].text = ig.global.fullQuestion[ig.global.currentQuestion].three;
			    
			    if (ig.global.fullQuestion[ig.global.currentQuestion].userAnswer == buttons[i].option)
			    {
				buttons[i].selected = true;
			    }
			    
			    break;
			
			case 4:			    
			    buttons[i].text = ig.global.fullQuestion[ig.global.currentQuestion].four;
			    
			    if (ig.global.fullQuestion[ig.global.currentQuestion].userAnswer == buttons[i].option)
			    {
				buttons[i].selected = true;
			    }
			    
			    break;			
		    }				
		}		
	    }
	    
	    var buttons = ig.game.getEntitiesByType(EntityOptionButton);
	    this.questionFont.draw("Valor: " + ig.global.fullQuestion[ig.global.currentQuestion].value, 570, 370, ig.Font.ALIGN.LEFT)
        },	
	
	secondsToMinutes: function (seconds)
	{
	    var minutes = Math.floor(seconds / 60);	    
	    return "" + minutes + ":" + (seconds % 60).toFixed(0);
	},
	
	ajustTextString: function (questionText, textMaxWidth)
	{
	    if (textMaxWidth < 300)
		return "";
	
	    var bufferText = "";
	    var para = questionText.split('\n');	    
	    for (var j = 0; j < para.length; j++)
	    {
		if (para[j] != null && para[j].trim() != "")
		{
		    var words = para[j].split(' ');
		    
		    var currentWidth = 0;
		    for (var i = 0; i < words.length; ++i)
		    {
			currentWidth += this.font12.widthForString(words[i] + " ");
			
			if (currentWidth >= textMaxWidth)
			{
			    bufferText += "\n";
			    currentWidth = 0;
			}
			
			bufferText += words[i] + " ";
		    }
		}
		
		bufferText += "\n";
	    }
	    
	    return bufferText;
	}
    });
});